package com.intelligentmeterreadingsys.waterlist.querywaterlist.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKPlanNode;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.RouteOverlay;
import com.baidu.mapapi.TransitOverlay;
import com.intelligentmeterreadingsys.MapApplication;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.util.BaiDuGpsUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;

import dbhelper.XmlNameHelper;

public class QueryRoutePlanMap extends MapActivity {
    // 定位图层
    public MyLocationOverlay mLocationOverlay = null;

    public String[] date = null;

    public MapView mMapView = null; // 地图View
    public MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用

    public String type = "公交";

    public LocationListener mLocationListener = null;// create时注册此listener，Destroy时需要Remove

    public MKPlanNode enNode = null;// 终点

    public MKPlanNode snNode = null;// 起点

    public Spinner spinner = null;

    public MKLocationManager locationMan = null;// 定位管理

    public static final int ITEM0 = Menu.FIRST;// 系统值

    public String locationtype = "gps";

    private final static int DIALOG = 1;
    public boolean isinit = true;

    public String adds = "";

    public Button button;// 查询按钮

    public boolean isSerch = false;

    public boolean isStop = true;

    public OverItemT itme;

    public int n = 0;

    public boolean isOk = false;

    public String city;

    public Double Latitude;

    public Double Longitude;

    @Override
    protected void onCreate(Bundle bundle) {

	super.onCreate(bundle);
	setContentView(R.layout.routeplan);
	SharedPreferenceUtil sp = new SharedPreferenceUtil(this);
	city = sp.getValue(XmlNameHelper.CITY);
	enNode = new MKPlanNode();
	snNode = new MKPlanNode();
	mMapView = (MapView) findViewById(R.id.bmapView);

	// 初始化终点
	Intent intent = getIntent();
	if (intent.getDoubleExtra("latitude", 0.0) > 0.0) {

	    GeoPoint point = new GeoPoint((int) (intent.getDoubleExtra("latitude", 0.0) * 1E6), (int) (intent.getDoubleExtra("longitude", 0.0) * 1E6));
	    Latitude = intent.getDoubleExtra("latitude", 0.0);
	    Longitude = intent.getDoubleExtra("longitude", 0.0);
	    enNode.pt = point;
	    adds = intent.getStringExtra("adds");
	}
	init();
    }

    @Override
    protected boolean isRouteDisplayed() {

	return false;
    }

    @Override
    protected void onPause() {
	MapApplication app = (MapApplication) this.getApplication();
	app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
	mLocationOverlay.disableMyLocation();

	app.mBMapMan.stop();
	super.onPause();
    }

    @Override
    protected void onResume() {
	MapApplication app = (MapApplication) this.getApplication();
	locationInit();
	app.mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
	app.mBMapMan.getLocationManager().setNotifyInternal(1, 10);
	mLocationOverlay.enableMyLocation();

	app.mBMapMan.start();
	super.onResume();
    }

    /**
     * 初始化控件并设置参数
     */
    public void init() {
	spinner = (Spinner) findViewById(R.id.mBtn_spinner);

	button = (Button) findViewById(R.id.mBtn_query);

	button.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		isSerch = true;
		isStop = true;
		isOk = false;
		Toast.makeText(QueryRoutePlanMap.this, "正在定位请等待", Toast.LENGTH_LONG).show();
		new Thread() {

		    @Override
		    public void run() {
			while (isStop) {
			    if (snNode.pt != null) {
				Message msg = myHandler.obtainMessage();
				msg.what = 1;
				myHandler.sendMessage(msg);
				isStop = false;
			    }
			    try {
				Thread.sleep(500);
			    } catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			    }
			}
			super.run();
		    }

		}.start();

	    }

	});

	spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		type = arg0.getItemAtPosition(arg2).toString();

	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> arg0) {
		type = "公交";

	    }
	});
	MapApplication app = (MapApplication) this.getApplication();
	mLocationListener = new MyLocationListen();

	if (app.mBMapMan == null) {
	    app.mBMapMan = new BMapManager(getApplication());
	    app.mBMapMan.init(app.mStrKey, new MapApplication.MyGeneralListener());
	}
	app.mBMapMan.start();
	// 初始化地图Activity
	super.initMapActivity(app.mBMapMan);
	// 得到地图层的控制权，可以用它控制和驱动平移和缩放
	MapController bMapController = mMapView.getController();
	// 设置地图ZOOM级别
	bMapController.setZoom(18);
	mMapView.setBuiltInZoomControls(true);
	// 设置在缩放动画过程中也显示overlay,默认为不绘制
	mMapView.setDrawOverlayWhenZooming(true);
	// 设置定位中心
	mMapView.getController().animateTo(enNode.pt);
	mMapView.invalidate();
	// 添加定位图层
	mLocationOverlay = new MyLocationOverlay(this, mMapView);
	mMapView.getOverlays().add(mLocationOverlay);

	// 初始化搜索模块，注册事件监听
	mSearch = new MKSearch();
	locationMan = app.mBMapMan.getLocationManager();

	mSearch.init(app.mBMapMan, new MyMKSearchListen());

    }

    /**
     * 收索模块监听器
     * 
     * @author king
     * 
     */
    public class MyMKSearchListen implements MKSearchListener {

	@Override
	public void onGetTransitRouteResult(MKTransitRouteResult res, int error) {

	    if (error != 0 || res == null) {
		mMapView.getOverlays().clear();
		mMapView.invalidate();
		Toast.makeText(QueryRoutePlanMap.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
		return;
	    }
	    TransitOverlay routeOverlay = new TransitOverlay(QueryRoutePlanMap.this, mMapView);
	    // 此处仅展示一个方案作为示例
	    routeOverlay.setData(res.getPlan(0));
	    mMapView.getOverlays().clear();
	    mMapView.getOverlays().add(routeOverlay);
	    n = mMapView.getOverlays().size() - 1;
	    mMapView.getOverlays().add(new MyOverlay(enNode.pt, adds));

	    mMapView.invalidate();
	    mMapView.getController().animateTo(res.getStart().pt);
	    isOk = true;
	    isSerch = false;
	}

	@Override
	public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {

	}

	@Override
	public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
	    // TODO Auto-generated method stub

	}

	@Override
	public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
	    System.out.println("架车");
	    if (error != 0 || res == null) {
		Toast.makeText(QueryRoutePlanMap.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
		mMapView.getOverlays().clear();
		mMapView.invalidate();
		return;
	    }
	    RouteOverlay routeOverlay = new RouteOverlay(QueryRoutePlanMap.this, mMapView);
	    routeOverlay.setData(res.getPlan(0).getRoute(0));
	    mMapView.getOverlays().clear();
	    mMapView.getOverlays().add(routeOverlay);
	    n = mMapView.getOverlays().size() - 1;
	    mMapView.getOverlays().add(new MyOverlay(enNode.pt, adds));
	    mMapView.invalidate();
	    mMapView.getController().animateTo(res.getStart().pt);
	    isOk = true;
	    isSerch = false;
	}

	@Override
	public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {

	}

	@Override
	public void onGetAddrResult(MKAddrInfo arg0, int arg1) {

	}

	@Override
	public void onGetRGCShareUrlResult(String arg0, int arg1) {

	}

	@Override
	public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) {

	    if (error != 0 || res == null) {
		Toast.makeText(QueryRoutePlanMap.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
		mMapView.getOverlays().clear();
		mMapView.invalidate();
		return;
	    }
	    RouteOverlay routeOverlay = new RouteOverlay(QueryRoutePlanMap.this, mMapView);
	    // 此处仅展示一个方案作为示例
	    routeOverlay.setData(res.getPlan(0).getRoute(0));

	    mMapView.getOverlays().clear();
	    mMapView.getOverlays().add(routeOverlay);
	    n = mMapView.getOverlays().size() - 1;
	    Drawable marker = getResources().getDrawable(R.drawable.a_key_to_upload);
	    // 得到需要标在地图上的资源
	    // mMapView.getOverlays().add(new OverItemT(enNode.pt,marker,
	    // QueryRoutePlanMap.this));
	    mMapView.getOverlays().add(new MyOverlay(enNode.pt, adds));
	    mMapView.invalidate();
	    mMapView.getController().animateTo(res.getStart().pt);
	    isOk = true;
	    isSerch = false;

	}
    }

    /**
     * 定位监听器
     * 
     * @author king
     * 
     */
    public class MyLocationListen implements LocationListener {

	@Override
	public void onLocationChanged(Location location) {
	    if (location == null) {
		return;
	    }

	    if (isSerch) {
		GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		snNode.pt = pt;
		Drawable marker = getResources().getDrawable(R.drawable.location); // 得到需要标在地图上的资源

		itme = new OverItemT(pt, marker, QueryRoutePlanMap.this, location);

		mMapView.getOverlays().add(itme); // 添加ItemizedOverlay实例到mMapView
		mMapView.getController().animateTo(snNode.pt);
		mMapView.invalidate();
	    }

	    if (isOk) {
		GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		mMapView.getOverlays().remove(mMapView.getOverlays().size() - 1);
		Drawable marker = getResources().getDrawable(R.drawable.location); // 得到需要标在地图上的资源

		itme = new OverItemT(pt, marker, QueryRoutePlanMap.this, location);

		mMapView.getOverlays().add(itme); // 添加ItemizedOverlay实例到mMapView
		mMapView.getController().animateTo(snNode.pt);
		mMapView.invalidate();
	    }

	}
    }

    /**
     * 定位初始化
     */
    public void locationInit() {
	if (locationtype.equals("gps")) {
	    locationMan.enableProvider(MKLocationManager.MK_GPS_PROVIDER);
	    locationMan.disableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
	} else if (locationtype.equals("network")) {
	    locationMan.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
	    locationMan.disableProvider(MKLocationManager.MK_GPS_PROVIDER);
	}

    }

    /**
     * 自定义文本标注
     * 
     * @author king
     * 
     */
    public class MyOverlay extends Overlay {
	private String adds;
	private GeoPoint geoPoint;

	public MyOverlay(GeoPoint geoPoint, String adds) {
	    this.adds = adds;
	    this.geoPoint = geoPoint;
	}

	Paint paint = new Paint();

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {

	    // 在天安门的位置绘制一个String
	    Point point = mMapView.getProjection().toPixels(geoPoint, null);
	    paint.setTextSize(17);
	    paint.setAntiAlias(true);
	    paint.setStrokeWidth(3);
	    if (adds == null || adds.equals("")) {
		adds = "没有精确地址";
	    }
	    int k = adds.length() % 8 > 0 ? adds.length() / 8 + 1 : adds.length() / 8;

	    if (k == 1) {
		paint.setColor(Color.BLUE);
		canvas.drawText(adds, point.x + 30, point.y - 30, paint);
	    } else {
		for (int i = 0; i < k; i++) {
		    String s = "";
		    if (adds.length() <= 8) {

			s = adds.substring(i * 8, adds.length());

		    } else {
			if (i == k - 1) {
			    s = adds.substring(i * 8, adds.length());
			} else {
			    s = adds.substring(i * 8, (i + 1) * 8);
			}
		    }
		    paint.setColor(Color.BLUE);
		    canvas.drawText(s, point.x + 30, point.y - 30 - (k - i - 1) * 20, paint);

		}
	    }

	    paint.setColor(Color.BLACK);
	    canvas.drawLine(point.x, point.y, point.x + 20, point.y - 40, paint);
	    canvas.drawLine(point.x, point.y, point.x + 20, point.y - 20, paint);
	    canvas.drawLine(point.x + 20, point.y - 20, point.x + 180, point.y - 20, paint);
	    canvas.drawLine(point.x + 180, point.y - 20, point.x + 180, point.y - 30 - k * 20, paint);
	    canvas.drawLine(point.x + 180, point.y - 30 - k * 20, point.x + 20, point.y - 30 - k * 20, paint);
	    canvas.drawLine(point.x + 20, point.y - 40, point.x + 20, point.y - 30 - k * 20, paint);
	}

    }

    /**
     * 点击事件标注
     * 
     * @author king
     * 
     */
    public class OverItemT extends ItemizedOverlay<OverlayItem> {

	private GeoPoint geopoint;
	private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();
	private Context mContext;

	public OverItemT(GeoPoint geopoint, Drawable marker, Context context, Location location) {
	    super(boundCenterBottom(marker));
	    this.mContext = context;
	    this.geopoint = geopoint;

	    Double d = BaiDuGpsUtil.GetShortDistance(location.getLongitude(), location.getLatitude(), Longitude, Latitude);
	    GeoList.add(new OverlayItem(geopoint, "p1", "这是你的位置,离终点还有" + d + "米"));
	    populate();
	    System.out.println("-----" + d);

	}

	@Override
	protected OverlayItem createItem(int arg0) {
	    // TODO Auto-generated method stub
	    return GeoList.get(0);
	}

	@Override
	public int size() {
	    // TODO Auto-generated method stub
	    return GeoList.size();
	}

	@Override
	// 处理当点击事件
	protected boolean onTap(int i) {
	    Toast.makeText(this.mContext, GeoList.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
	    return true;
	}
    }

    /**
     * 判断GPS是否存在或开启
     */
    public boolean openGPSSettings() {
	LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);

	if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

	    return true;
	}
	Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
	Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
	startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
	return false;
    }

    /**
     * 搜索路线
     */
    public void Serch() {
	if (type.equals("公交")) {
	    // 设置公交策略
	    mSearch.setTransitPolicy(MKSearch.ECAR_TIME_FIRST);

	    mSearch.transitSearch(city, snNode, enNode);

	} else if (type.equals("驾车")) {
	    // 设置架车测略
	    mSearch.setDrivingPolicy(MKSearch.ECAR_DIS_FIRST);
	    mSearch.drivingSearch(city, snNode, city, enNode);
	} else if (type.equals("步行")) {

	    mSearch.walkingSearch(city, snNode, city, enNode);
	}

    }

    Handler myHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    if (msg.what == 1) {
		Toast.makeText(QueryRoutePlanMap.this, "定位成功,正在搜索路线图！", Toast.LENGTH_SHORT).show();
		Serch();
	    }
	    super.handleMessage(msg);
	}

    };
}
